import 'package:aweb5/util/FileUtil.dart';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'dart:io';
//import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:progress_dialog/progress_dialog.dart';
import 'package:aweb5/config/Config.dart';
import 'package:http_parser/http_parser.dart';
import 'package:aweb5/util/LogUtil.dart';
//import 'package:http/http.dart';
/*
 * 封装 restful 请求
 *
 * GET、POST、DELETE、PATCH
 * 主要作用为统一处理相关事务：
 *  - 统一处理请求前缀；
 *  - 统一打印请求信息；
 *  - 统一打印响应信息；
 *  - 统一打印报错信息；
 */
class HttpUtils {
  /// global dio object
  static Dio dio;

  /// default options
//  static const String API_PREFIX = "http://hhnrest2yxbk.test.freshqiao.com/";
  static const int CONNECT_TIMEOUT = 10000;
  static const int RECEIVE_TIMEOUT = 3000;

  /// http request methods
  static const String GET = 'get';
  static const String POST = 'post';
  static const String PUT = 'put';
  static const String PATCH = 'patch';
  static const String DELETE = 'delete';

  /// request method
  static Future<Map> request(String url, {data, method}) async {
    data = data ?? {};
    method = method ?? 'GET';

    /// restful 请求处理
    /// /gysw/search/hist/:user_id        user_id=27
    /// 最终生成 url 为     /gysw/search/hist/27
    data.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    /// 打印请求相关信息：请求地址、请求方式、请求参数
    print('请求地址：【' + method + '  ' + url + '】');
    print('请求参数：' + data.toString());

    Dio dio = createInstance();
    var result;

    try {
      Response response = await dio.request(url,
          data: data, options: new Options(method: method));

      result = response.data;

      /// 打印响应相关信息
      print('响应数据：' + response.toString());
    } on DioError catch (e) {
      /// 打印请求失败相关信息
      print('请求出错：' + e.toString());
     // Fluttertoast.showToast(msg: "请求出错");
      rethrow ;
    }

    return result;
  }

  static Future<Map<String,dynamic>> get(String url, {data, method}) async {
    data = data ?? {};
    method =   'GET';
    data["api_code"]="appApi";
    data["api_password"]="hLnhNoxSijGiv8t1";
    /// restful 请求处理
    /// /gysw/search/hist/:user_id        user_id=27
    /// 最终生成 url 为     /gysw/search/hist/27
    data.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    /// 打印请求相关信息：请求地址、请求方式、请求参数
    print('请求地址：【' + method + '  ' + url + '】');
    print('请求参数：' + data.toString());

    Dio dio = createInstance();
    var result;

    try {
      Response response = await dio.request(url,
          queryParameters: data, options: new Options(method: method));

      result = response.data;
      result = json.decode(result);
      /// 打印响应相关信息
      LogUtil.d("响应数据：${url}"+ response.toString());
//      print('响应数据：${url}' + response.toString());
    } on DioError catch (e) {
      /// 打印请求失败相关信息
      print('请求出错：' + e.toString());
     // Fluttertoast.showToast(msg: "请求出错");
      dio.reject(e);
     // rethrow;
    }

    return result;
  }




  static Future<Map> getAppend(String url, {data, method}) async {
    data = data ?? {};
    method =   'GET';

    /// restful 请求处理
    /// /gysw/search/hist/:user_id        user_id=27
    /// 最终生成 url 为     /gysw/search/hist/27
    data.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    /// 打印请求相关信息：请求地址、请求方式、请求参数
    print('请求地址：【' + method + '  ' + url + '】');
    print('请求参数：' + data.toString());

    Dio dio = createInstance();
    var result;

    try {
      Response response = await dio.request(url,
          queryParameters: data, options: new Options(method: method));

      result = response.data;

      /// 打印响应相关信息
      print('响应数据：' + response.toString());
    } on DioError catch (e) {
      /// 打印请求失败相关信息
      print('请求出错：' + e.toString());
     // Fluttertoast.showToast(msg: "请求出错");
      dio.reject(e);
     // rethrow;
    }

    return result;
  }

  static Future<Map<String,dynamic>> post(String url, {Map<String,dynamic>data, method}) async {
    data = data ?? {};
    data["api_code"]="appApi";
    data["api_password"]="hLnhNoxSijGiv8t1";
    method =   'POST';

    /// restful 请求处理
    /// /gysw/search/hist/:user_id        user_id=27
    /// 最终生成 url 为     /gysw/search/hist/27
//    data.forEach((key, value) {
//      if (url.indexOf(key) != -1) {
//        url = url.replaceAll(':$key', value.toString());
//      }
//    });

    /// 打印请求相关信息：请求地址、请求方式、请求参数
    print('请求地址：【' + method + '  ' + url + '】');
    print('请求参数：' + data.toString());

    Dio dio = createInstance();
    var result;

    try {
      Response response = await dio.request(url,
          data: data, options: new Options(method: method));

      result = response.data;
      result = json.decode(result);

      /// 打印响应相关信息
//      print('响应数据：${url}' + response.toString());
      print("runtype${result.runtimeType}");
      LogUtil.d("响应数据：${url}"+ response.toString());
    } on DioError catch (e) {
      /// 打印请求失败相关信息
      print('请求出错：' + e.toString());
     // Fluttertoast.showToast(msg: "请求出错");
      dio.reject(e);
     // rethrow;
    }

    return result;
  }


//  static Future fetchUploadProductBanner(String path) async{
//    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
//    var image = await MultipartFile.fromFile(
//      path,
//      filename: name,
//    );
//    FormData formData = FormData.fromMap({
//      "image": image
//    });
//    var response = await http.post(HttpConstants.UPLOAD_PRODUCT_BANNER_IMAGE,data: formData);
//    return ImageBean.fromJson(response.data);
//  }


  static Future<Map<String,dynamic>> upload(File file,bool image) async{
//    MediaType.parse("multipart/form-data")

    var postData = FormData.fromMap({
      "file": await MultipartFile.fromFile(
          file.path, filename: DateTime.now().millisecondsSinceEpoch.toString()+"${image?".jpeg":".mp4"}",contentType:MediaType.parse("multipart/form-data"))
    });
//                          var responce = await Request().getInstance().upload("https://yujun.store/upload.php",postData, (send, total){
    //                print("$send $total");
//                              });//这里我用的我自己封装的上传方法，print("$send $total");这里是Dio的onSendProgress监听，我发现不怎么好用，就没去研究
    var result;
    try{
      if(image){
        var responce = await Dio().post("${Config.requestApi}plug/upload/upImage",data:postData,onSendProgress: (int sent, int total) {
          print("$sent $total"); //send是上传的大小 total是总文件大小
        },options: Options(contentType: "multipart/form-data"));
        result = responce.data;
        result = json.decode(result);
        LogUtil.d("响应数据：plug/upload/upImage"+ responce.toString());
        print(">${responce}");
      }else{
        var responce = await Dio().post("${Config.requestApi}plug/upload/upVideo",data:postData,onSendProgress: (int sent, int total) {
          print("$sent $total "); //send是上传的大小 total是总文件大小
        },options: Options(contentType: "multipart/form-data"));
        print(">${responce}");
        result = responce.data;
        result = json.decode(result);
        LogUtil.d("响应数据：plug/upload/upVideo"+ responce.toString());
      }
    }on DioError catch (e) {
      /// 打印请求失败相关信息
      print('请求出错：' + e.toString());
      // Fluttertoast.showToast(msg: "请求出错");
      Dio().reject(e);
      // rethrow;
    }
    return result;


  }

  /// 创建 dio 实例对象
  static Dio createInstance() {
    if (dio == null) {
      /// 全局属性：请求前缀、连接超时时间、响应超时时间
      BaseOptions options = new BaseOptions(
//        baseUrl: API_PREFIX,
        connectTimeout: CONNECT_TIMEOUT,
        receiveTimeout: RECEIVE_TIMEOUT,
      );
      dio = new Dio(options);


//      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
//          (client) {
//        client.findProxy = (url) {
//          ///设置代理 电脑ip地址
//          return "PROXY 192.168.0.102:8888";
////          return "PROXY 192.168.1.93:8888";
//
//          ///不设置代理
////          return 'DIRECT';
//        };
//
//        ///忽略证书
//        client.badCertificateCallback = (X509Certificate cert, String host, int port) => true;
//      };


//      dio = new Dio(options);
//      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client){
//        client.findProxy = (url){
//          return "PROXY 192.168.1.93:8888";
//        };
//      };
    }

    return dio;
  }

  static Dio downloadDio;
  static Dio createDownloadInstance(){

    if (downloadDio == null) {
      /// 全局属性：请求前缀、连接超时时间、响应超时时间
      BaseOptions options = new BaseOptions(
//        baseUrl: API_PREFIX,
        connectTimeout: CONNECT_TIMEOUT,
        receiveTimeout: 30000,
      );
      downloadDio = new Dio(options);


    }
    return downloadDio;
  }

  /// 清空 dio 对象
  static clear() {
    dio = null;
  }


  static Future<Response> downloadImgs(String resUrl, String savePath,List<String> list,List<bool> finish,Function function,int num,ProgressDialog pr,int index,{bool saveToGallery=false}) async {
//    Dio dio = createInstance();
    Dio dio = createDownloadInstance();
    //还好我之前写过服务端代码，不然我根本没有相对路劲的概念
    Response response = await dio.download(resUrl, savePath,
        onReceiveProgress: (int loaded, int total) {
          //取精度，如：56.45%

        },
        );
//    Fluttertoast.showToast(msg: "${response.statusCode}");
//    Fluttertoast.showToast(msg: "${savePath}");

    if(response.statusCode == 200){
//      print("savePath${savePath}");
//      list.add(savePath);

      if(saveToGallery){

        if(savePath.endsWith("jpg")){
        String derterminUrl= await FileUtil.saveBase64toGalleryFromUrl(savePath);
        if(Platform.isAndroid){
          list.add(derterminUrl);
        }else{
          list.add(derterminUrl);
        }
        }





      }else{

        if(Platform.isAndroid){
          list.add("file://"+savePath);
        }else{
          list.add(savePath);
        }

      }



      print(">>>$savePath");
//      print(">>>d$derterminUrl");
//      print("determinPath${derterminUrl}");


//      list.add(savePath);
      finish.add(true);

    }else{
      finish.add(false);

    }
    pr.update(
      progress: finish.length.toDouble(),
      message: "请稍候……",
      progressWidget: Container(
          padding: EdgeInsets.all(8.0),
          child: CircularProgressIndicator()),
      maxProgress: num.toDouble(),
      progressTextStyle: TextStyle(
          color: Colors.black,
          fontSize: 13.0,
          fontWeight: FontWeight.w400),
      messageTextStyle: TextStyle(
          color: Colors.black,
          fontSize: 19.0,
          fontWeight: FontWeight.w600),
    );

    if(finish.length == num){
      Fluttertoast.showToast(msg: "下载成功");
      function();
    }
  }
  static Future<Response> downloadMultiFile(String resUrl, String savePath,List<String> list,List<bool> finish,Function function,int num,ProgressDialog pr,int index) async {
//    Dio dio = createInstance();
    Dio dio = createDownloadInstance();
    //还好我之前写过服务端代码，不然我根本没有相对路劲的概念
    Response response = await dio.download(resUrl, savePath,
        onReceiveProgress: (int loaded, int total) {
          //取精度，如：56.45%

        },
        );
//    Fluttertoast.showToast(msg: "${response.statusCode}");
//    Fluttertoast.showToast(msg: "${savePath}");

    if(response.statusCode == 200){
//      print("savePath${savePath}");
//      list.add(savePath);


    String derterminUrl = savePath;
      if(savePath.endsWith("jpg")){
        derterminUrl = await FileUtil.saveBase64toGalleryFromUrl(savePath);

      }


      print(">>>$savePath");
      print(">>>d$derterminUrl");
//      print("determinPath${derterminUrl}");
      list.add(derterminUrl);
//      list.add(savePath);
      finish.add(true);

    }else{
      finish.add(false);

    }
    pr.update(
      progress: finish.length.toDouble(),
      message: "请稍候……",
      progressWidget: Container(
          padding: EdgeInsets.all(8.0),
          child: CircularProgressIndicator()),
      maxProgress: num.toDouble(),
      progressTextStyle: TextStyle(
          color: Colors.black,
          fontSize: 13.0,
          fontWeight: FontWeight.w400),
      messageTextStyle: TextStyle(
          color: Colors.black,
          fontSize: 19.0,
          fontWeight: FontWeight.w600),
    );

    if(finish.length == num){
      Fluttertoast.showToast(msg: "下载成功");
      function();
    }
  }


  int index(String path){

    return int.parse(path.split("x")[1]);

  }
  static Future<Response> downloadOneImg(String resUrl, String savePath ,Function function,ProgressDialog pr ,{bool saveToGallery=false}) async {
//    Dio dio = createInstance();
    Dio dio = createDownloadInstance();
    //还好我之前写过服务端代码，不然我根本没有相对路劲的概念
    Response response = await dio.download(resUrl, savePath,
      onReceiveProgress: (int loaded, int total) {
        //取精度，如：56.45%
        pr.update(
          progress: loaded.toDouble(),
          message: "请稍候……",
          progressWidget: Container(
              padding: EdgeInsets.all(8.0),
              child: CircularProgressIndicator()),
          maxProgress: total.toDouble(),
          progressTextStyle: TextStyle(
              color: Colors.black,
              fontSize: 13.0,
              fontWeight: FontWeight.w400),
          messageTextStyle: TextStyle(
              color: Colors.black,
              fontSize: 19.0,
              fontWeight: FontWeight.w600),
        );
      },
    );


    if(response.statusCode == 200){


      String derterminUrl ="";
      if(saveToGallery){
        derterminUrl = await FileUtil.saveBase64toGalleryFromUrl(savePath);

        if(Platform.isAndroid){
          if(derterminUrl!=null){
            function(derterminUrl);
          }else{
            function("");
          }
        }else{
          if(derterminUrl!=null){
            function(derterminUrl);
          }else{
            function("");
          }
        }


      }else{

        if(Platform.isAndroid){
          function("file://"+savePath);
        }else{
          function(savePath);
        }

      }




    }else{
      function("");
     Fluttertoast.showToast(msg: "下载出错");
    }
    
  }

  static Future<Response> downloadVideoFile(String resUrl, String savePath, Function function,ProgressDialog pr ) async {
//    Dio dio = createInstance();
    Dio dio = createDownloadInstance();
    //还好我之前写过服务端代码，不然我根本没有相对路劲的概念
    Response response = await dio.download(resUrl, savePath,
      onReceiveProgress: (int loaded, int total) {
        //取精度，如：56.45%
        pr.update(
          progress: loaded.toDouble(),
          message: "请稍候……",
          progressWidget: Container(
              padding: EdgeInsets.all(8.0),
              child: CircularProgressIndicator()),
          maxProgress: total.toDouble(),
          progressTextStyle: TextStyle(
              color: Colors.black,
              fontSize: 13.0,
              fontWeight: FontWeight.w400),
          messageTextStyle: TextStyle(
              color: Colors.black,
              fontSize: 19.0,
              fontWeight: FontWeight.w600),
        );
//        Fluttertoast.showToast(msg: "$progress");
      },
    );

    if(response.statusCode == 200){

      function(true);

    }else{
     function(false);
     Fluttertoast.showToast(msg: "下载出错");
    }
//    Fluttertoast.showToast(msg: savePath,toastLength: Toast.LENGTH_LONG);

  }


//    static void requestDownload(String url,String filename,String savePath,Function downloadCallback) async {
//      FlutterDownloader.registerCallback(downloadCallback);
//       await FlutterDownloader.enqueue(
//          url: url,
//          headers: {"auth": "test_for_sql_encoding"},
//          savedDir: savePath,
//           fileName: filename,
//          showNotification: true,
//          openFileFromNotification: true);
//    }


}
